﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sinacor.Infra.UI.Messaging;
using Sinacor.Infra.UI.Messaging.Internal;
using System.Timers;
using System.Threading;

namespace Sinacor.Infra.UI.Session
{
    public class ServerKeepAlive
    {
        private int _intervalToSendKeepAlive = 2; //Minutos
        private bool _stillRunning;
        private bool _stillSendingKeepAlive;
        private MessageManager _messageManager;
        private IServerKeepAlive _serverKeepAlive;

        public ServerKeepAlive(IServerKeepAlive serverKeepAlive)
        {
            _serverKeepAlive = serverKeepAlive;

            _messageManager = MessageManager.GetInstance();
            _messageManager.OnInternalMessageArrival += new MessageManager.InternalMessageArrivalDelegate(_messageManager_OnInternalMessageArrival);
        }

        public void Start()
        {
            _stillSendingKeepAlive = true;
            _stillRunning = true;

            Thread thr = new Thread(new ThreadStart(Cronometer));

            thr.Start();
        }

        public void Stop()
        {
            _stillSendingKeepAlive = false;
            _stillRunning = false;
        }

        private void Cronometer()
        {
            int TIME_TO_SEND_KEEP_ALIVE = _intervalToSendKeepAlive * 60 * 1000;


            while (_stillRunning)
            {
                for(int i = 0; i < TIME_TO_SEND_KEEP_ALIVE && _stillRunning; i = i + 500)
                    Thread.Sleep(500);

                SendServerKeepAlive();
            }
        }

        private void SendServerKeepAlive()
        {
            if(_stillSendingKeepAlive)
                _serverKeepAlive.SendServerKeepAlive();
        }

        void _messageManager_OnInternalMessageArrival(InternalMessage internalMessage)
        {
            string messageId = internalMessage.MessageId;

            if (messageId == MessageIds.Application.SNC_APPLICATION_INACTIVITY)
                PauseSendKeepAlive();
            else if (messageId == MessageIds.Application.SNC_APPLICATION_UNBLOCKED)
                UnPauseSendKeepAlive();
        }

        private void UnPauseSendKeepAlive()
        {
            _stillSendingKeepAlive = true;
        }

        private void PauseSendKeepAlive()
        {
            _stillSendingKeepAlive = false;
        }

        public int IntervalToSendKeepAlive
        {
            get { return _intervalToSendKeepAlive; }
            set { _intervalToSendKeepAlive = value; }
        }
    }
}
